<template>
  <div class="app-container">
    <!-- 提交表单区-->
    <div id="dashFormArea">
      <el-form ref="dashForm" :model="dashForm" :rules="rules" :inline="true">
        <el-form-item
          prop="host"
        >
          <el-autocomplete
            v-model="dashForm.host"
            :fetch-suggestions="querySearchAsync"
            value-key="host"
            size="small"
            placeholder="请输入主机IP"
            @select="handleSelect"
          />
        </el-form-item>
        <el-form-item>
          <div class="block">
            <el-date-picker
              v-model="dashForm.dateRange"
              size="small"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            />
          </div>
        </el-form-item>
        <el-button type="primary" size="small" icon="el-icon-check" @click="paraSubmit('dashForm')" />
      </el-form>
    </div>
    <panel-group @handleSetLineChartData="handleSetLineChartData" />
    <div id="charts">
      <div ref="allChart" class="chart" :style="{width:'100%', height:'300px'}" />
    </div>
  </div>
</template>

<script>
import { drawChart } from '@/api/charts'
import { getHosts } from '@/api/hosts'
import { getHardware } from '@/api/hardware'
import { getTransaction } from '@/api/transaction'
import { mills2secs } from '@/api/utils'
import resize from '@/api/resize'
import PanelGroup from './components/PanelGroup'

export default {
  components: {
    PanelGroup
  },
  mixins: [resize],
  data() {
    return {
      type: 'cpu',
      hosts: [],
      timeout: null,
      dashForm: {
        host: '',
        dateRange: []
      },
      hardwareChart: [],
      transactionChart: [],
      chartData: [],
      threshold: null,
      rules: {
        host: [
          {
            required: true,
            message: '请输入主机IP',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.initData()
  },
  async mounted() {
    // 同步获取主机IP再根据默认值刷新图表
    await getHosts(this).then(data => {
      // 更新默认主机
      this.hosts = data
      this.dashForm.host = data[0].host
      this.getThreshold()
    })
    this.postPara(this.type)
  },
  methods: {
    initData() {
      var endTime = new Date()
      // 最近10天
      var startTime = new Date().setTime(endTime.getTime() - 1000 * 60 * 60 * 24 * 10)
      this.dashForm.dateRange[0] = new Date(startTime)
      this.dashForm.dateRange[1] = new Date(endTime)
    },
    handleSetLineChartData(type) {
      this.type = type
      this.postPara(type)
    },
    querySearchAsync(queryString, cb) {
      var host = this.hosts
      var results = queryString ? host.filter(this.createStateFilter(queryString)) : host

      clearTimeout(this.timeout)
      this.timeout = setTimeout(() => {
        cb(results)
      }, 300 * Math.random())
    },
    createStateFilter(queryString) {
      return (host) => {
        return (host.host.indexOf(queryString.toLowerCase()) === 0)
      }
    },
    handleSelect(item) {
      console.log(item)
    },
    async postPara(type) {
      const formData = new FormData()
      var startTime = this.dashForm.dateRange[0].getTime().toString()
      var endTime = this.dashForm.dateRange[1].getTime().toString()
      formData.append('host', this.dashForm.host)
      formData.append('start_time', mills2secs(startTime))
      formData.append('end_time', mills2secs(endTime))
      if (type === 'trans') {
        // 交易数据
        await getTransaction(this, formData).then(data => {
          this.chartData = data
        })
      } else {
        // 硬件信息
        await getHardware(this, formData, type).then(data => {
          this.chartData = data
        })
      }
      drawChart(this, this.chartData, type, this.threshold)
    },
    paraSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.postPara(this.type)
        } else {
          this.$message.error('刷新失败，请输入主机IP！！')
        }
      })
    },
    getThreshold() {
      this.$axios.get('/api/threshold').then(resp => {
        this.threshold = resp.data
      }).catch(function(error) {
        console.log(error)
      })
    }
  }
}
</script>

<style scoped>
  .el-button--primary {
    color: #fff;
    background-color: #304156;
    border-color: #304156;
    margin-top: 3px;
  }

  .app-container {
    /*background-color: #394056;*/
    height: fit-content;
  }

  .chart {
    /*padding: 20px;*/
    margin-top: 4px;
  }
</style>
